package com.lingo.ffmpegdemo.lg.utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Random;

/**
 * @author watson
 * @date 2021/5/8 16:05
 * @Description: TODO
 **/
public class MyFileUtils {
    public static void cut() {
        File file = new File("C:\\Users\\Administrator\\Desktop\\picture\\shipin\\02极限.mp4");
//        int num = 10;//分割文件的数量
        Random random = new Random();
        long num = random.nextInt(5) + 2;

        //使文件字节数+1，保证取到所有的字节
        long lon = file.length() / num + 1L;

        try {
            RandomAccessFile raf1 = new RandomAccessFile(file, "r");
            //值设置越小，则各个文件的字节数越接近平均值，但效率会降低，这里折中，取1024
            byte[] bytes = new byte[1024];
            int len = -1;
            for (int i = 1; i <= num; i++) {
                String name = "D:\\ffmpegMedia\\temp\\02极限" + i + ".mp4";
                File file2 = new File(name);
                RandomAccessFile raf2 = new RandomAccessFile(file2, "rw");

                while ((len = raf1.read(bytes)) != -1) {//读到文件末尾时，len返回-1，结束循环
                    raf2.write(bytes, 0, len);
                    if (raf2.length() > lon) {
                        //当生成的新文件字节数大于lon时，结束循环
                        break;
                    }
                }
                raf2.close();
            }
            raf1.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
        cut();
        System.out.println("=================end===============");
    }
}
